﻿using System;
using System.Xml.Linq;
using HTB.DevFx;
using Maple.Weixin.MP.Exceptions;
using Maple.Weixin.MP.Helpers;

namespace Maple.Weixin.MP.Entities.Messages
{
    public abstract class ResponseMessageBase : MessageBase
    {
        protected ResponseMessageBase() : this(false) { }

        protected ResponseMessageBase(bool encrypt) {
            this.Encrypt = encrypt;
        }

        public virtual ResponseMessageType MessageType {
            get { return ResponseMessageType.Text; }
        }

        public bool Encrypt { get; private set; }

        public XDocument ToXDocument() {
            var service = ObjectService.GetObject<IWeixinService>();
            if (Encrypt) {
                var messageXml = "";
                var timestamp = DateTime.Now.Ticks.ToString();
                var nonce = DateTime.Now.Ticks.ToString();
                var returnCode = service.EncryptMessage(ToXDocumentBase().ToString(), timestamp, nonce, ref messageXml);
                if (returnCode != 0) {
                    throw new MessageEncryptingException(returnCode);
                }
                return XDocument.Parse(messageXml);
            }
            return ToXDocumentBase();
        }

        public virtual XDocument ToXDocumentBase() {
            var document = new XDocument(
                new XElement("xml",
                    new XElement("ToUserName", new XCData(ToUserName)),
                    new XElement("FromUserName", new XCData(FromUserName)),
                    new XElement("CreateTime", WeixinHelper.GetWeixinDateTime(CreateTime)),
                    new XElement("MsgType", new XCData(MessageType.ToString().ToLower()))
                    ));
            return document;
        }
    }
}
